package com.doyoung.appicker.view;

import java.util.ArrayList;





import java.util.HashMap;

import com.doyoung.appicker.R;
import com.doyoung.appicker.controller.SongController;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainListFragment extends Fragment{
	
	private static MainListFragment INSTANCE;
	
	public static MainListFragment getInstance(){
		if (INSTANCE == null){
			INSTANCE = new MainListFragment();
		}
		return INSTANCE;
	}
	
	private boolean initFlag = false;
	final ArrayList<HashMap<String, String>> songList = new ArrayList<HashMap<String, String>>();
	
	public static final String KEY_SONG = "song";
	public static final String KEY_ID = "id";
	public static final String KEY_TITLE = "title";
	public static final String KEY_ARTIST = "artist";
	public static final String KEY_DURATION = "duration";
	public static final String KEY_THUMB_URL = "thumb_url";
	
	private String TAG = "MainListFragment";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d(TAG, "MainListFragment onCreateView() Called");
		
		View view = inflater.inflate(R.layout.fragment_main_list, container, false);
		final ListView listview = (ListView)view.findViewById(R.id.main_listView);
		
		if (!initFlag){
			initFlag = true;
			
//			final ArrayList<HashMap<String, String>> songList = new ArrayList<HashMap<String, String>>();
		
			for (int i=0; i<10; i++){
				HashMap<String, String> map = new HashMap<String, String>();

				map.put(KEY_ID, Integer.toString(i));
				map.put(KEY_TITLE, "Someone Like You");
				map.put(KEY_ARTIST, "Adele");
				map.put(KEY_DURATION, "4:47");
				map.put(KEY_THUMB_URL, "http://api.androidhive.info/music/images/adele.png");

				songList.add(map);
			}
		}

		final SongController ac = new SongController(getActivity(), songList);

		listview.setAdapter(ac);
		listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, final View view,
					int position, long id) {
				final int pos = position;

				view.animate().setDuration(1000).alpha(0).withEndAction(new Runnable() {
					@Override
					public void run() {
						if (pos < songList.size()){
							songList.remove(pos);
							ac.notifyDataSetChanged();
							view.setAlpha(1);
						}
						else{
							Log.d(TAG, "pos : " + pos + " < songList.size():" + songList.size());
						}
					}
				});
			}
		});

		return view;
	}
}
